package program.Loop;

import Exceptions.ElementPlacementError;
import Exceptions.IllegalCoordinateException;
import Exceptions.PickupError;
import Exceptions.ShootException;
import Exceptions.TerminationError;
import program.Atom;
import program.SExprList;
import program.SExpression;
import program.Command.Command;
import program.Condition.Condition;
import roborally.Robot;

/**
 * A class representing the IF command.
 * 
 * @author Jef Keijers/Bachelor of Science: Informatics
 * @version 1.0
 */
public class If extends Command {

	/**
	 * This constructor instantiate a new IF condition with a given condition and the given if-and else-part.
	 * @param 	condition
	 * @param 	ifpart
	 * @param 	elsepart
	 */
	public If(Condition condition,Command ifpart,Command elsepart) {
		this.condition=condition;
		this.ifpart=ifpart;
		this.elsepart=elsepart;
	}

	/**
	 * This method executes one step of the ifpart (if the condition is true) else executes one step of the elsepart. 
	 * Afterwards return the rest of the command that still has to be executed.
	 * 
	 * @throws PickupError 
	 * @throws TerminationError 
	 * @throws IllegalCoordinateException 
	 * @throws ShootException 
	 * @throws ElementPlacementError 
	 */
	@Override
	public Command execute(Robot robot) throws ShootException, IllegalCoordinateException, TerminationError, PickupError, ElementPlacementError  {

		if (condition.execute(robot)) {
			return ifpart.execute(robot);
		} else {
			return elsepart.execute(robot);
		}
	}
	
	/**
	 * Returns the SExpression representation of the IF.
	 */
	@Override
	public SExpression toSExpression() {
		SExprList sexpr = new SExprList();
		sexpr.add(new Atom("if"));
		sexpr.add(ifpart.toSExpression());
		sexpr.add(elsepart.toSExpression());
		return sexpr;
	}
	/**
	 * Instance variable representing the condition of the IF.
	 */
	private Condition condition;
	/**
	 * Instance variable representing the ifpart command.
	 */
	private Command ifpart;
	/**
	 * Instance variable representing the elsepart command.
	 */
	private Command elsepart;

	
}
